﻿using AutoMapper;
using Infrastructure;
using Standard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using YSL.Application.Ysl_Dto.Input.LockOrUnlock;
using YSL_Domain.Model;

namespace YSL.Application.Services.LockOrUnLock
{
    public class ProductLockService : IProductLockService
    {
        private readonly MesRepository<YSL_WORKORDER> _workOrderRepository;
        private readonly IMapper _mapper;
        private readonly MesRepository<YSL_PRODUCT_LOCK> _lockRepository;


        public ProductLockService(MesRepository<YSL_WORKORDER> workOrderRepository, IMapper mapper, MesRepository<YSL_PRODUCT_LOCK> lockRepository)
        {
            _workOrderRepository = workOrderRepository;
            _mapper = mapper;
            _lockRepository = lockRepository;
        }
        /// <summary>
        /// 添加产品锁定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public ApiResult<int> AddProductLock(AddProductLockInput input)
        {
            var model = _workOrderRepository.GetEntity(x => x.CODEID == input.CODEID && x.ISDELETE == false);
            if (model == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "工单不存在/被删除"
                };
            }
            if (model.LOCK_STATUE == "锁定")
            {

                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "工单已锁定，请先解锁"
                };
            }
            var lockModel = new YSL_PRODUCT_LOCK()
            {
                PRODUCTID = "PL" + YitIdHelper.NextId().ToString(),
                CODEID = input.CODEID,

                PRODUCE_TYPE = input.WORKORDER_TYPE,
                LOCK_STARTTIME = input.LOCK_STARTTIME,
                LOCL_ENDTIME = input.LOCL_ENDTIME,
                LOCK_REASON = input.LOCK_REASON,
                PRODUCTION_PROCESSES = model.PROCESS_PROGRESS,
                LOCK_STATUES = "锁定",
                CREATETIME = DateTime.Now,
                ISDELETE = false,
                CREATE_TIME = DateTime.Now,

            };
            model.LOCK_STATUE = "锁定";
            _workOrderRepository.Update(model);
            var res = _lockRepository.Add(lockModel);
            if (res > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.Success,
                    Message = "产品锁定成功",
                    ResultData = res
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "产品锁定失败",
                    ResultData = res
                };
            }
        }
        /// <summary>
        ///  查询产品锁定列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiPaging<YSL_PRODUCT_LOCK> GetProductLockList(GetProductLockListInput input)
        {
            var list = _lockRepository.GetQueryable(x => x.ISDELETE == false && x.LOCK_STATUES == "锁定");

            if (!string.IsNullOrEmpty(input.CODEID))
            {
                list = list.Where(x => x.CODEID.Contains(input.CODEID));
            }

            if (!string.IsNullOrEmpty(input.PRODUCE_TYPE))
            {
                list = list.Where(x => x.PRODUCE_TYPE.Contains(input.PRODUCE_TYPE));
            }

            if (input.LOCK_STARTTIME != null)
            {
                var startDate = input.LOCK_STARTTIME.Value.Date;
                var endDate = startDate.AddDays(1);
                list = list.Where(x => x.LOCK_STARTTIME >= startDate && x.LOCK_STARTTIME < endDate);
            }

            if (input.LOCL_ENDTIME != null)
            {
                var endDate = input.LOCL_ENDTIME.Value.Date;
                var nextDay = endDate.AddDays(1);
                list = list.Where(x => x.LOCL_ENDTIME >= endDate && x.LOCL_ENDTIME < nextDay);
            }

            var result = new ApiPaging<YSL_PRODUCT_LOCK>()
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                PageDatas = list.OrderByDescending(x => x.CREATETIME).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList(),
                //PageDatas = list.ToList(),
                TotalCount = list.Count(),
                TotalPage = list.Count() / input.PageSize
            };
            return result;
        }

        /// <summary>
        /// 查询工单产品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<YSL_WORKORDER> GetWorkOrderEntity(AddProductLockInput input)
        {
            var model = _workOrderRepository.GetQueryable( x=>x.ISDELETE == false && x.LOCK_STATUE == "已解锁");
           
            if (input.WORKORDER_TYPE != null) 
            {
                model = model.Where(x=>x.WORKORDER_TYPE==input.WORKORDER_TYPE);
 
                
            }
            if (input.CODEID != null) 
            {
                var codeId = input.CODEID.Trim();
                model = model.Where(x=>x.CODEID== codeId);
            }
            var list=     model.First();
            if ((list == null))
            {
                return new ApiResult<YSL_WORKORDER>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "工单不存在/工单被锁定无法查看"
                };
            }
            else
            {
                return new ApiResult<YSL_WORKORDER>()
                {
                    Code = ApiCode.Success,
                    Message = "查询成功",
                    ResultData = list
                };
            }
        }
        /// <summary>
        /// 批量解锁产品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> UnProductLock(UnProductLockInput input)
        {
            if (input?.PRODUCTIDs == null || input.PRODUCTIDs.Count == 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.ParameterError,
                    Message = "未指定要解锁的产品ID",
                    ResultData = 0
                };
            }

            // 1. 查询要解锁的产品锁定记录
            var lockModels = _lockRepository.GetQueryable(
                x => input.PRODUCTIDs.Contains(x.PRODUCTID) && x.LOCK_STATUES == "锁定" && x.ISDELETE == false
            ).ToList();

            if (lockModels.Count == 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.ParameterError,
                    Message = "未找到要解锁的产品",
                    ResultData = 0
                };
            }

            // 2. 批量更新产品锁定状态
            foreach (var lockModel in lockModels)
            {
                lockModel.LOCK_STATUES = "已解锁";
                lockModel.UPDATE_TIME = DateTime.Now;
            }
            var lockRes = _lockRepository.BatchUpdate(lockModels);

            // 3. 获取所有相关的CODEID
            var codeIds = lockModels.Select(x => x.CODEID).Distinct().ToList();

            // 4. 查询并批量更新工单的锁定状态
            var workOrders = _workOrderRepository.GetQueryable(
                x => codeIds.Contains(x.CODEID) && x.LOCK_STATUE == "锁定" && x.ISDELETE == false
            ).ToList();

            foreach (var workOrder in workOrders)
            {
                workOrder.LOCK_STATUE = "已解锁";
                workOrder.UPDATE_TIME = DateTime.Now;
            }
            var workOrderRes = workOrders.Count > 0 ? _workOrderRepository.BatchUpdate(workOrders) : 0;

            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                Message = "批量解锁成功",
                ResultData = lockRes // 可根据需要返回 lockRes + workOrderRes
            };
        }

        /// <summary>
        /// 解锁产品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //public ApiResult<int> UnProductLock(UnProductLockInput input)
        //{
        //    var model = _lockRepository.GetEntity(x => x.PRODUCTID == input.PRODUCTID);
        //    if (model == null)
        //    {
        //        return new ApiResult<int>()
        //        {
        //            Code = ApiCode.ParameterError,
        //            Message = "产品不存在"
        //        };
        //    }
        //    model.LOCK_STATUES = "已解锁";
        //    var res = _lockRepository.Update(model);
        //    if (res > 0)
        //    {
        //        return new ApiResult<int>()
        //        {
        //            Code = ApiCode.Success,
        //            Message = "产品解锁成功",
        //            ResultData = res
        //        };
        //    }
        //    else
        //    {
        //        return new ApiResult<int>()
        //        {
        //            Code = ApiCode.ParameterError,
        //            Message = "产品解锁失败",
        //            ResultData = res
        //        };
        //    }



        //}
        /// <summary>
        /// 修改产品锁定时间
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> UpdateProductLock(UpdateProductLockInput input)
        {
            var model = _lockRepository.GetEntity(x => x.PRODUCTID == input.PRODUCTID);
            if (model == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "产品不存在"
                };
            }
            model.LOCK_STARTTIME = input.LOCK_STARTTIME;
            model.LOCL_ENDTIME = input.LOCL_ENDTIME;
            model.UPDATE_TIME = DateTime.Now;
            var res = _lockRepository.Update(model);
            if (res > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.Success,
                    Message = "产品锁定时间修改成功",
                    ResultData = res
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "产品锁定时间修改失败",
                    ResultData = res
                };
            }
        }
    }
}
